import { CustomPage } from '/engine/index';
import { getUserInfo, updateUserInfo } from '../../services/user';
import { parseIDCard, calculateBMI } from '../../utils/index';

const HeightList = Array.from({ length: 250 }, (_, i) => `${i + 1}cm`);
const WeightList = Array.from({ length: 150 }, (_, i) => `${i + 1}kg`);
const RequiredFieldsMapping = {
  realName: '就诊人姓名',
  realCardNo: '身份证号',
  height: '身高',
  weight: '体重',
};

function checkEmptyFields(data) {
  for (const [key, label] of Object.entries(RequiredFieldsMapping)) {
    const value = data[key];

    // 如果是字符串，判断是否为空白
    if (typeof value === 'string' && !value.trim()) {
      return { isEmpty: true, emptyField: label };
    }

    // 如果是数字，判断是否为 null/undefined 或 NaN
    if (typeof value === 'number' && isNaN(value)) {
      return { isEmpty: true, emptyField: label };
    }

    // 如果是 undefined 或 null
    if (value === null || value === undefined) {
      return { isEmpty: true, emptyField: label };
    }
  }

  return { isEmpty: false, emptyField: null };
}

CustomPage({
  data: {
    realName: '',
    realCardNo: '',
    cardNoValid: true,
    birthday: '',
    gender: '',
    height: '160',
    weight: '50',
    userInfo: {},
    columns: [
      {
        values: HeightList,
        className: 'column1',
        defaultIndex: 159,
        title: '111',
      },
      {
        values: WeightList,
        className: 'column1',
        defaultIndex: 49,
      },
    ],
  },
  async onLoad() {
    const userInfo = await getUserInfo();
    if (userInfo?.data?.idCardNumber) {
      wx.redirectTo({ url: '/pages/chat/index' });
      return;
    }
    this.setData({ userInfo: userInfo?.data });
  },
  onChangeRealName(event) {
    this.setData({
      realName: event.detail,
    });
  },
  onChangeCardNo(event) {
    const { valid, birthday, gender } = parseIDCard(event.detail);
    this.setData({
      cardNoValid: valid,
      birthday,
      gender,
      realCardNo: event.detail,
    });
  },
  onChangeHeighInfo(event) {
    const { value } = event.detail;
    this.setData({
      height: value?.[0],
      weight: value?.[1],
    });
  },
  async onClickStart() {
    const {
      userInfo,
      realName,
      realCardNo,
      cardNoValid,
      birthday,
      gender,
      height,
      weight,
    } = this.data;
    const { isEmpty, emptyField } = checkEmptyFields(this.data);

    let tipMsg = '';
    if (!cardNoValid) {
      tipMsg = '身份信息校验不通过，请返回重新填写';
    } else if (isEmpty) {
      tipMsg = `${emptyField}信息不能为空，请返回重新填写`;
    }
    if (tipMsg) {
      wx.showModal({
        title: '提示',
        content: tipMsg,
      });
      return;
    }
    const { bmi } = calculateBMI(
      Number(height.replace('cm', '')),
      Number(weight.replace('kg', ''))
    );
    const resp = await updateUserInfo({
      ...userInfo,
      userName: realName,
      idCardNumber: realCardNo,
      birthday,
      sex: gender,
      height: Number(height.replace('cm', '')),
      weight: Number(weight.replace('kg', '')),
      bmi,
    });
    if (resp?.code === 200) {
      wx.redirectTo({ url: '/pages/chat/index' });
      return;
    }
    wx.showModal({
      title: '提示',
      content: resp?.msg,
    });
  },
});
